import logger from './logger';
import { requestErrorLog } from '../middlewares/request_log';

const errorData = function (result = {}) {
  result.success = false;
  const { e, err } = result;
  if (e) throw new Error('NG');
  if (!err) result.err = '未知错误';
  logger.error(`errorData. err = ${result.err}`);
  return result;
};

const successData = function (result = {}) {
  result.success = true;
  const { message, m, msg } = result;
  if (!message) result.message = '未知成功';
  if (!m) result.m = '未知成功';
  if (!msg) result.msg = '未知成功';
  logger.debug(`successData. message = ${result.message} || m = ${result.m} || msg = ${result.msg}`);
  return result;
};

export function errorJson(req, res, result = {}) {
  requestErrorLog(req, res);
  res.json(errorData(result));
}

export function successJson(req, res, result = {}) {
  res.json(successData(result));
}

export function errorRender(req, res, result = {}, page) {
  if (!page) page = 'notify';
  res.render(page, errorData(result));
}

export function successRender(req, res, result = {}, page) {
  if (!page) page = 'notify';
  res.render(page, successData(result));
}
